use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub enum TaskStatus
{
	Unfinished,		// 未完成
	Completed,		// 已完成
}

#[derive(Serialize, Deserialize)]
pub struct Task{
	pub id: u32,
	pub title: String,
	pub description: String,
	pub status: TaskStatus,
	pub create_time: String,		// 任务创建时间
	pub update_time: String,		// 任务更新时间
}

#[derive(Serialize, Deserialize)]
pub struct TaskList
{
	next_id: u32,
	task_list: Vec<Task>,
}

impl TaskList {
	pub fn new() -> Self {
		Self { next_id: 1, task_list: Vec::new() }
	}

	pub fn add_task(&mut self, title: String, description: String) -> &Task {
		let task = Task {
			id: self.next_id,
			title,
			description,
			status: TaskStatus::Unfinished,
			create_time: chrono::Utc::now().to_string(),
			update_time: chrono::Utc::now().to_string(),
		};

		self.task_list.push(task);
		self.next_id += 1;
		self.task_list.last().unwrap()
	}

	pub fn finish_task(&mut self, id: u32) -> bool {
		let idx = self.find_task(id);
		if idx >= 0 {
			let task = &mut self.task_list[idx as usize];
			task.status = TaskStatus::Completed;
			task.update_time = chrono::Utc::now().to_string();
			true
		}
		else {
			false
		}
	}

	pub fn remove_task(&mut self, id: u32) {
		let idx = self.find_task(id);
		if idx >= 0 {
			self.task_list.remove(idx as usize);
		}
		else {
			println!("任务不存在或已被删除!");
		}
	}

	fn find_task(&self, id: u32) -> i32 { 
		if let Some(pos) = self.task_list.iter().position(|task|task.id == id) {
			return pos as i32;
		}
		return -1;
	}

	pub fn show_all_task(&self) {
		if self.task_list.is_empty() {
			println!("任务列表为空！");
		}
		else {
			for task in self.task_list.iter() {
				let status = match task.status {
					TaskStatus::Unfinished => "待完成",
					TaskStatus::Completed => "已完成",
				};
				println!("任务ID: {}, 任务描述: {}, 任务状态: {}, 任务创建时间: {}, 任务更新时间: {}", task.id,
					task.description, status, task.create_time, task.update_time);
			}
		}
	}
}